<?php

declare(strict_types=1);


namespace App\Utils\Upload;




use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Server\Response;
use MongoDB\GridFS\Bucket;

class View
{
    public $type;

    /**
     * @var string
     */
    public $stream;

    /**
     * @var string
     */
    public $originName;

    /**
     * @Inject()
     * @var Response
     */
    protected $response;

    public function __construct(Bucket $grid = null, string $md5 = null)
    {
        if ($grid && $md5) {
            $image = $grid->openDownloadStreamByName($md5);
            $fileDoc = $grid->getFileDocumentForStream($image);
            $this->type = $fileDoc->contentType;
            $this->originName = $fileDoc->aliases['origin_name'];
            $this->stream = stream_get_contents($image);
        }
    }

    /**
     * @return mixed
     */
    public function response()
    {
        return $this->response->withContent($this->stream)->withHeader('Content-type', $this->type);
    }

    /**
     * 生成访问路径
     * @param $md5
     * @param string $path
     * @param null $host
     * @return string
     */
    public function fullPath($md5, $path = '/view/', $host = null)
    {
        return ($host ?? env('APP_HOST')). $path . $md5;
    }


    /**
     * 下载
     * @return mixed
     */
    public function downloadFile()
    {
        return $this->response->withContent($this->stream)
                ->withHeader('Content-type', $this->type)
                ->withHeader('Content-Disposition', "attachment;filename=$this->originName")
                ->withHeader('Content-Encoding', 'binary')
                ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
    }

}